package com.alexgaoyh.weixin.index;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alexgaoyh.weixin.util.http.HttpClientUtilss;
import com.alexgaoyh.weixin.util.json.JSONUtilss;
import com.alexgaoyh.weixin.util.properties.WeixinAPPropertiesUtilss;
import com.alexgaoyh.weixin.util.vo.AccessTokenVO;
import com.alexgaoyh.weixin.util.vo.OpenIDVO;
import com.alexgaoyh.weixin.util.vo.UserInfoListVO;
import com.alexgaoyh.weixin.util.vo.UserInfoVO;

@Controller
@RequestMapping(value="")
public class IndexController {

	@RequestMapping(value = "/index")
	public ModelAndView index(ModelAndView model, HttpServletRequest request) {
		
		List<String> headImgUrlList = new ArrayList<String>();
		
		String accessTokenJSONStr = HttpClientUtilss.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+WeixinAPPropertiesUtilss.getAppID()+"&secret="+WeixinAPPropertiesUtilss.getAppsecret()+"");
		AccessTokenVO accessTokenVO = JSONUtilss.readValue(accessTokenJSONStr, AccessTokenVO.class);
		
		String userInfoListJSONStr = HttpClientUtilss.get("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessTokenVO.getAccess_token() + "&next_openid=");
		UserInfoListVO userInfoListVO = JSONUtilss.readValue(userInfoListJSONStr, UserInfoListVO.class);
		
		OpenIDVO openIDVO = userInfoListVO.getData();
		for(String _str : openIDVO.getOpenid()) {
			String userInfoJSONStr = HttpClientUtilss.get("https://api.weixin.qq.com/cgi-bin/user/info?access_token="+ accessTokenVO.getAccess_token() +"&openid=" + _str + "&lang=zh_CN");
			UserInfoVO userInfoVO = JSONUtilss.readValue(userInfoJSONStr, UserInfoVO.class);
			System.out.println(userInfoVO.getHeadimgurl());
			headImgUrlList.add(userInfoVO.getHeadimgurl());
		}
		
		model.addObject("headImgUrlList", headImgUrlList);
		model.setViewName("index/index");
		return model;
	}
}
